<template>
  <div class="patients-container">
    <el-card class="search-card">
      <div class="search-header">
        <div class="left">
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索患者姓名/手机号"
            class="search-input"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </div>
      </div>
    </el-card>

    <el-card class="patient-list">
      <el-table :data="patientList" stripe style="width: 100%">
        <el-table-column type="expand">
          <template #default="props">
            <div class="expand-detail">
              <el-tabs>
                <el-tab-pane label="就医记录">
                  <div class="medical-records">
                    <div v-for="record in props.row.medicalRecords" 
                         :key="record.id" 
                         class="record-item"
                    >
                      <div class="record-header">
                        <span class="hospital">{{ record.hospital }}</span>
                        <span class="department">{{ record.department }}</span>
                        <span class="date">{{ record.date }}</span>
                      </div>
                      <div class="record-content">
                        <p><strong>主诉：</strong>{{ record.description }}</p>
                        <p><strong>诊断：</strong>{{ record.diagnosis }}</p>
                        <p><strong>处方：</strong>{{ record.prescription }}</p>
                        <p><strong>备注：</strong>{{ record.notes }}</p>
                      </div>
                    </div>
                    <el-empty v-if="!props.row.medicalRecords?.length" description="暂无就医记录" />
                  </div>
                </el-tab-pane>
                <el-tab-pane label="健康信息">
                  <div class="health-info">
                    <div class="info-row">
                      <span class="label">血型：</span>
                      <span>{{ props.row.healthInfo.bloodType }}</span>
                    </div>
                    <div class="info-row">
                      <span class="label">过敏史：</span>
                      <span>{{ props.row.healthInfo.allergies || '无' }}</span>
                    </div>
                    <div class="info-row">
                      <span class="label">既往病史：</span>
                      <span>{{ props.row.healthInfo.medicalHistory || '无' }}</span>
                    </div>
                    <div class="info-row">
                      <span class="label">长期用药：</span>
                      <span>{{ props.row.healthInfo.medications || '无' }}</span>
                    </div>
                  </div>
                </el-tab-pane>
                <el-tab-pane label="服务记录">
                  <div class="service-records">
                    <el-timeline>
                      <el-timeline-item
                        v-for="record in props.row.serviceRecords"
                        :key="record.id"
                        :timestamp="record.date"
                        :type="record.status === 'completed' ? 'success' : 'primary'"
                      >
                        <h4>{{ record.serviceType }}</h4>
                        <p>医院：{{ record.hospital }}</p>
                        <p>科室：{{ record.department }}</p>
                        <p>备注：{{ record.notes }}</p>
                      </el-timeline-item>
                    </el-timeline>
                    <el-empty v-if="!props.row.serviceRecords?.length" description="暂无服务记录" />
                  </div>
                </el-tab-pane>
              </el-tabs>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="scope">
            {{ scope.row.gender === 'male' ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="age" label="年龄" width="80" />
        <el-table-column prop="phone" label="联系电话" width="150" />
        <el-table-column prop="emergencyContact" label="紧急联系人" width="120" />
        <el-table-column prop="emergencyPhone" label="紧急联系电话" width="150" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              link
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              type="success" 
              link
              @click="handleAddRecord(scope.row)"
            >
              添加记录
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑患者信息对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="editingPatient ? '编辑患者信息' : '添加患者'"
      width="600px"
    >
      <el-form :model="patientForm" :rules="rules" ref="patientFormRef" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="patientForm.name" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="patientForm.gender">
            <el-radio value="male">男</el-radio>
            <el-radio value="female">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="patientForm.age" :min="0" :max="150" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="patientForm.phone" />
        </el-form-item>
        <el-form-item label="紧急联系人" prop="emergencyContact">
          <el-input v-model="patientForm.emergencyContact" />
        </el-form-item>
        <el-form-item label="紧急电话" prop="emergencyPhone">
          <el-input v-model="patientForm.emergencyPhone" />
        </el-form-item>
        <el-form-item label="血型" prop="bloodType">
          <el-select v-model="patientForm.bloodType">
            <el-option label="A型" value="A" />
            <el-option label="B型" value="B" />
            <el-option label="O型" value="O" />
            <el-option label="AB型" value="AB" />
          </el-select>
        </el-form-item>
        <el-form-item label="过敏史">
          <el-input
            v-model="patientForm.allergies"
            type="textarea"
            :rows="2"
            placeholder="如有过敏史，请填写"
          />
        </el-form-item>
        <el-form-item label="既往病史">
          <el-input
            v-model="patientForm.medicalHistory"
            type="textarea"
            :rows="2"
            placeholder="如有既往病史，请填写"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPatientForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加就医记录对话框 -->
    <el-dialog
      v-model="recordDialogVisible"
      title="添加就医记录"
      width="600px"
    >
      <el-form :model="recordForm" :rules="recordRules" ref="recordFormRef" label-width="100px">
        <el-form-item label="就诊医院" prop="hospital">
          <el-input v-model="recordForm.hospital" />
        </el-form-item>
        <el-form-item label="就诊科室" prop="department">
          <el-input v-model="recordForm.department" />
        </el-form-item>
        <el-form-item label="就诊日期" prop="date">
          <el-date-picker
            v-model="recordForm.date"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="主诉" prop="description">
          <el-input
            v-model="recordForm.description"
            type="textarea"
            :rows="2"
          />
        </el-form-item>
        <el-form-item label="诊断结果" prop="diagnosis">
          <el-input
            v-model="recordForm.diagnosis"
            type="textarea"
            :rows="2"
          />
        </el-form-item>
        <el-form-item label="处方" prop="prescription">
          <el-input
            v-model="recordForm.prescription"
            type="textarea"
            :rows="2"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="recordForm.notes"
            type="textarea"
            :rows="2"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="recordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRecordForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 搜索表单
const searchForm = reactive({
  keyword: ''
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 患者列表数据
const patientList = ref([
  {
    id: 1,
    name: '张三',
    gender: 'male',
    age: 45,
    phone: '13800138000',
    emergencyContact: '李四',
    emergencyPhone: '13900139000',
    healthInfo: {
      bloodType: 'A',
      allergies: '青霉素过敏',
      medicalHistory: '高血压、糖尿病',
      medications: '格列美脲片 2mg/天'
    },
    medicalRecords: [
      {
        id: 1,
        date: '2024-01-15',
        hospital: '协和医院',
        department: '内分泌科',
        description: '血糖控制不稳定',
        diagnosis: '2型糖尿病',
        prescription: '调整降糖药物剂量',
        notes: '建议一周后复查'
      }
    ],
    serviceRecords: [
      {
        id: 1,
        date: '2024-01-15',
        serviceType: '陪诊服务',
        hospital: '协和医院',
        department: '内分泌科',
        status: 'completed',
        notes: '按时完成陪诊服务'
      }
    ]
  }
])

// 编辑相关
const editDialogVisible = ref(false)
const editingPatient = ref(null)
const patientFormRef = ref(null)
const patientForm = reactive({
  name: '',
  gender: 'male',
  age: 0,
  phone: '',
  emergencyContact: '',
  emergencyPhone: '',
  bloodType: '',
  allergies: '',
  medicalHistory: ''
})

// 添加记录相关
const recordDialogVisible = ref(false)
const recordFormRef = ref(null)
const recordForm = reactive({
  hospital: '',
  department: '',
  date: '',
  description: '',
  diagnosis: '',
  prescription: '',
  notes: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

const recordRules = {
  hospital: [
    { required: true, message: '请输入就诊医院', trigger: 'blur' }
  ],
  department: [
    { required: true, message: '请输入就诊科室', trigger: 'blur' }
  ],
  date: [
    { required: true, message: '请选择就诊日期', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入主诉', trigger: 'blur' }
  ],
  diagnosis: [
    { required: true, message: '请输入诊断结果', trigger: 'blur' }
  ]
}

// 搜索相关方法
const handleSearch = () => {
  // TODO: 实现搜索逻辑
  console.log('搜索关键词：', searchForm.keyword)
}

const resetSearch = () => {
  searchForm.keyword = ''
  handleSearch()
}

// 编辑患者信息
const handleEdit = (patient) => {
  editingPatient.value = patient
  Object.assign(patientForm, patient)
  editDialogVisible.value = true
}

// 添加就医记录
const handleAddRecord = (patient) => {
  editingPatient.value = patient
  recordDialogVisible.value = true
}

// 提交患者表单
const submitPatientForm = async () => {
  if (!patientFormRef.value) return

  try {
    await patientFormRef.value.validate()
    // TODO: 调用保存API
    
    if (editingPatient.value) {
      // 更新患者信息
      const index = patientList.value.findIndex(p => p.id === editingPatient.value.id)
      if (index !== -1) {
        patientList.value[index] = { ...patientList.value[index], ...patientForm }
      }
      ElMessage.success('患者信息更新成功')
    } else {
      // 添加新患者
      patientList.value.push({
        id: Date.now(),
        ...patientForm
      })
      ElMessage.success('患者添加成功')
    }
    
    editDialogVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 提交就医记录
const submitRecordForm = async () => {
  if (!recordFormRef.value) return

  try {
    await recordFormRef.value.validate()
    // TODO: 调用保存API
    
    const patient = patientList.value.find(p => p.id === editingPatient.value.id)
    if (patient) {
      if (!patient.medicalRecords) {
        patient.medicalRecords = []
      }
      patient.medicalRecords.unshift({
        id: Date.now(),
        ...recordForm
      })
    }
    
    ElMessage.success('就医记录添加成功')
    recordDialogVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val
  // TODO: 重新加载数据
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  // TODO: 重新加载数据
}

onMounted(() => {
  // TODO: 获取患者列表数据
})
</script>

<style scoped lang="scss">
.patients-container {
  .search-card {
    margin-bottom: 20px;

    .search-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .left {
        display: flex;
        gap: 10px;

        .search-input {
          width: 300px;
        }
      }
    }
  }

  .patient-list {
    .expand-detail {
      padding: 20px;

      .medical-records {
        .record-item {
          border: 1px solid #ebeef5;
          border-radius: 4px;
          padding: 15px;
          margin-bottom: 15px;

          .record-header {
            margin-bottom: 10px;
            display: flex;
            gap: 20px;
            color: #606266;

            .hospital {
              font-weight: bold;
              color: #303133;
            }
          }

          .record-content {
            p {
              margin: 5px 0;
              color: #606266;

              strong {
                color: #303133;
              }
            }
          }
        }
      }

      .health-info {
        .info-row {
          margin-bottom: 15px;
          display: flex;

          .label {
            width: 100px;
            color: #909399;
          }
        }
      }

      .service-records {
        padding: 20px;
      }
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 